﻿using PersistentObject.Common.Exceptions;
using PersistentObject.Common.Schema;
using PersistentObject.Common.Sorts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersistentObject.Common
{
    public class BaseOrderByCreator
    {
        public Table MainTable { get; set; }

        public BaseDialect Dialect { get; set; }

        public BaseOrderByCreator(Table mainTable, BaseDialect dialect)
        {
            MainTable = mainTable;
            Dialect = dialect;
        }

        public string GetOrderByClause(OrderBy orderby)
        {
            if (orderby is OrderByProperty)
            {
                return GetOrderByClause(orderby as OrderByProperty);
            }
            else if (orderby is OrderByExpression)
            {
                return GetOrderByClause(orderby as OrderByExpression);
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        public string GetOrderByClause(OrderByProperty orderby)
        {
            Column column = MainTable.GetMappingColumn(orderby.PropertyName);
            if (column == null)
            {
                throw new UnknownPropertyNameException(string.Format("Unknown property name {0} for the type {1}", orderby.PropertyName, MainTable.TableName));
            }
            var columnAlias = Dialect.NamingPattern.GetColumnAlias(column);
            var orderByType = Dialect.NamingPattern.GetOrderByTypeClause(orderby.Type);
            var columnNameWithTableAliasInQuote = string.Format(orderby.Decoration, Dialect.NamingPattern.GetColumnNameWithTableAliasInQuote(column));
            string clause = string.Format("{0} {1}",
                columnNameWithTableAliasInQuote,
                orderByType);
            return clause;
        }

        public string GetOrderByClause(OrderByExpression orderby)
        {
            throw new NotImplementedException();
        }
    }
}
